//
//  AppDelegate.m
//  doubleEduStudents
//
//  Created by 盛洋 on 2021/1/4.
//  Copyright © 2021 shengYang. All rights reserved.
//

#import "AppDelegate.h"
#import "UIWindow+Extension.h"
#import "SCJumpViewController.h"
#import "ZYLauchMovieViewController.h"
#import "MainService.h"
#import "HomeVC.h"

#define WS(weakSelf)  __weak __typeof(&*self)weakSelf = self;
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //使用系统tabbar
    [self initRootViewController];
    
    //保存当前时间到本地
    [[DataService sharedService] SaveCurrentDayToLocal];
    [[MainService sharedService] initMainService:self.window];
    //注册友盟分享
    [[OpenAPIServices sharedService] setUmengAppKey];
    //友盟一键登录
    [UMConfigure initWithAppkey:@"6061885db8c8d45c13b569c0" channel:@"App Store"];
    [self setUMOneLogin];
    
    return YES;
}


- (void)initRootViewController{
    self.window = [[UIWindow alloc]init];
    self.window.frame = [[UIScreen mainScreen] bounds];

    /*
     * 已登陆
     */
    if (NSUDGetToken) {
        
        //引导页倒计时
        SCJumpViewController *jumpVC = [[SCJumpViewController alloc]init];
        BaseNavVC *nav = [[BaseNavVC alloc] initWithRootViewController: jumpVC];
        WS(weakSelf);
        jumpVC.blockMainViewController = ^{
            HomeVC *home = [[HomeVC alloc]initWithNibName:@"HomeVC" bundle:nil];
            BaseNavVC *nav = [[BaseNavVC alloc] initWithRootViewController: home];
            weakSelf.window.rootViewController = nav;
        };
        self.window.rootViewController = nav;
        
        //直接进入首页
//        BaseNavVC *nav = [[BaseNavVC alloc] init];
//        self.window.rootViewController = nav;
        
    }
    else {
        /*
         * 未登陆
         */
        LoginVC *login = [[LoginVC alloc]initWithNibName:@"LoginVC" bundle:nil];
        BaseNavVC *navLogin = [[BaseNavVC alloc] initWithRootViewController:login];
        self.window.rootViewController = navLogin;
   
       //开机视频
//        UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
//        ZYLauchMovieViewController *vc = [[ZYLauchMovieViewController alloc] init];
//        window.rootViewController = vc;
//        self.window = window;
//        [self.window makeKeyAndVisible];
    }
    
    //引导页面自定义页数
//    [self.window switchRootViewController];
    
    [self.window makeKeyAndVisible];
    
}


-(void)setUMOneLogin{
    //设置秘钥
       NSString *info = @"MFJQfjFMHKc5NGpjNLKwhA/wsYvF4RIzl4fClo5Ji6fllqOot9lzOrh957MsEHF0IoKy8yHYXYQDwk/IJBB/cIt7toOUMOed4cFRrtYtraVbONF6dLzX+e0jMKP1gnViZkjSucTgBU2HaQ+vXxXz41/Zzhrk9ALmECBal5PuK+6cfjqC1IGozHZodZ63ntfgTF7RwrnLTEchLzztTwzYvSMxdD6yyXk2DYwjPH8VYox42t/CJY1qmXaEAuLmjaOEYwzvUU/lpxZrYovztgMDbQ==";
       __weak typeof(self) weakSelf = self;
       [UMCommonHandler setVerifySDKInfo:info complete:^(NSDictionary * _Nonnull resultDic) {
           NSLog(@"设置SDK秘钥:--%@---",resultDic);
       }];
    
    
    // 检测当前环境是否支持一键登录，支不支持提前知道 (UMPNSAuthTypeLoginToken 检查一键登录环境 UMPNSAuthTypeVerifyToken 检查号码认证环境)
    __block BOOL support = YES;
    [UMCommonHandler checkEnvAvailableWithAuthType:UMPNSAuthTypeLoginToken complete:^(NSDictionary * _Nullable resultDic) {
        NSLog(@"是否支持一键登录:--%@---",resultDic);
        support = [PNSCodeSuccess isEqualToString:[resultDic objectForKey:@"resultCode"]];
    }];
    
    
    //1. 获取 VerifyToken
    [UMCommonHandler  getVerifyTokenWithTimeout:3 complete:^(NSDictionary * _Nonnull resultDic) {
        if ([PNSCodeSuccess isEqualToString:[resultDic objectForKey:@"resultCode"]] == NO) {
            NSLog(@"获取 VerifyToken失败");
            return ;
        }
        //2. 去服务器验证 VerifyToken
        NSString *token = [resultDic objectForKey:@"token"];
        NSLog(@"一键登录注册返回token:%@",token);
        dispatch_async(dispatch_get_main_queue(), ^{
            [UMCommonHandler cancelLoginVCAnimated:YES complete:nil];
        });
        
        //是否有sim卡
        if ([UMCommonUtils simSupportedIsOK]) {
            //1. 调用取号接口，加速授权页的弹起
            [UMCommonHandler accelerateLoginPageWithTimeout:3 complete:^(NSDictionary * _Nonnull resultDic) {
                if ([PNSCodeSuccess isEqualToString:[resultDic objectForKey:@"resultCode"]] == NO) {
                    NSLog(@"取号，加速授权页弹起失败");
                    return ;
                }
                
                //2. 调用获取登录Token接口，可以立马弹起授权页
                UMCustomModel *model = [weakSelf buildCustomModel:YES];
                model.supportedInterfaceOrientations = UIInterfaceOrientationMaskAllButUpsideDown;
                
                [UMCommonHandler getLoginTokenWithTimeout:3 controller:self.window.rootViewController model:model complete:^(NSDictionary * _Nonnull resultDic) {
                    
                    NSString *code = [resultDic objectForKey:@"resultCode"];
                    if ([PNSCodeLoginControllerPresentSuccess isEqualToString:code]) {
                        NSLog(@"弹起授权页成功");
                    } else if ([PNSCodeLoginControllerClickCancel isEqualToString:code]) {
                        NSLog(@"点击了授权页的返回");
                    } else if ([PNSCodeLoginControllerClickChangeBtn isEqualToString:code]) {
                        NSLog(@"点击切换其他登录方式按钮");
                        [UMCommonHandler cancelLoginVCAnimated:YES complete:^{
                            
                        }];
                    } else if ([PNSCodeLoginControllerClickLoginBtn isEqualToString:code]) {
                        if ([[resultDic objectForKey:@"isChecked"] boolValue] == YES) {
                            NSLog(@"点击了登录按钮，check box选中，SDK内部接着会去获取登陆Token");
                        } else {
                            NSLog(@"点击了登录按钮，check box选中，SDK内部不会去获取登陆Token");
                        }
                    } else if ([PNSCodeLoginControllerClickCheckBoxBtn isEqualToString:code]) {
                        NSLog(@"点击check box");
                    } else if ([PNSCodeLoginControllerClickProtocol isEqualToString:code]) {
                        NSLog(@"点击了协议富文本");
                    } else if ([PNSCodeSuccess isEqualToString:code]) {
                        //点击登录按钮获取登录Token成功回调
                        NSString *token = [resultDic objectForKey:@"token"];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [UMCommonHandler cancelLoginVCAnimated:YES complete:nil];
                        });
                        NSLog(@"--%@--",resultDic);
                        
                        //拿Token去服务器换手机号
                        
                    } else {
                            NSLog(@"获取登录Token失败");
                    }
                    NSLog(@"--%@--",resultDic);
                }];
            }];
        }
        
    }];
}

#pragma mark - applicationOpenURL-
- (UMCustomModel *)buildCustomModel:(BOOL)isAlert {
    if (isAlert) {
        return [UMModelCreate createAlert];
    } else {
        return [UMModelCreate createFullScreen];
    }
    
}
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    return [[OpenAPIServices sharedService] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
}

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [[OpenAPIServices sharedService] handleOpenURL:url];
}

//- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray * __nullable restorableObjects))restorationHandler
//{
//    if (![[UMSocialManager defaultManager] handleUniversalLink:userActivity options:nil]) {
//        // 其他SDK的回调
//    }
//    return YES;
//}


#pragma mark - UISceneSession lifecycle


//- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
//    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
//}


//- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
//}


#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"doubleEduStudents"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

@end
